﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RpcGenerator.CSharp
{
    class AsynCallbackGenerator
    {
        public static void Generate(IMessageSerializer serializer, List<MessageDescription> allDescriptions)
        {
            List<MessageDescription> allResponse = allDescriptions.Where(md => md.AsynMethod && !md.IsRequest).ToList();
            allResponse.ForEach(md => Generate(serializer, md));
        }

        private static void Generate(IMessageSerializer serializer, MessageDescription md)
        {
            serializer.NewLine();
            serializer.NewLine(string.Format("class {0}AsynCallback : RpcAsynCallback", md.Method.Method.Name));
            serializer.BeginBlock();
            {
                serializer.NewLine(string.Format("public {0}AsynCallback(RpcSessionService ss, bool encrypt, int opcode)", md.Method.Method.Name));
                serializer.NewLine("  :base(ss,encrypt,opcode)");
                serializer.BeginBlock();
                serializer.EndBlock();

                serializer.NewLine();
                string returnType = md.Fields[0].IsGenericType()?md.Fields[0].GenericTypeName:md.Fields[0].Type.Name;
                serializer.NewLine(string.Format("public void Return({0} returnValue)",returnType));
                serializer.BeginBlock();
                {
                    serializer.NewLine(string.Format("{0} response = new {0}();", md.Name));
                    md.Fields.ForEach(fieldDescription =>
                    {
                        serializer.NewLine(string.Format("response.{0} = {0};", fieldDescription.Name));
                    });
                    serializer.NewLine("Callback(response);");
                }
                serializer.EndBlock();
            }
            serializer.EndBlock();
        }
    }
}
